package demo.shiro;

import demo.entity.User;
import demo.entity.UserCompany;
import demo.service.UserCompanyService;
import demo.service.UserService;
import demo.util.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Shiro 账号 realm
 *
 * @author 肖溥博文
 * @version 1.2
 */
@Component
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserService userService;

    @Autowired
    UserCompanyService userCompanyService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    // 授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        AccountProfile primaryPrincipal = (AccountProfile) principalCollection.getPrimaryPrincipal();
        System.out.println(primaryPrincipal);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        if ("ADMIN".equalsIgnoreCase(primaryPrincipal.getPosition())) {
            simpleAuthorizationInfo.addRole("ADMIN");
        } else if ("HR".equalsIgnoreCase(primaryPrincipal.getPosition())) {
            simpleAuthorizationInfo.addRole("HR");
        } else {
            simpleAuthorizationInfo.addRole("user");
        }

        return simpleAuthorizationInfo;
    }

    // 认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;

        // 获取 uid
        String uid = jwtUtil.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();

        // 获取用户对象
        User user = userService.findUserByUid(Long.valueOf(uid));
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        // 获取并设置用户账户
        AccountProfile accountProfile = new AccountProfile();
        accountProfile.setId(user.getUid());

        UserCompany userCompany = (UserCompany) userCompanyService.findLatestUserCompanyByUid(user.getUid()).getData();
        if (userCompany != null) {
            // BeanUtil.copyProperties(userCompany, accountProfile);
            accountProfile.setPosition(userCompany.getPosition());
        }

        // 参数 1：账号
        // 参数 2：密码
        // 参数 3：当前 realm 的名字
        return new SimpleAuthenticationInfo(accountProfile, jwtToken.getCredentials(), getName());
    }
}
